$(function(){
	initRoomTable();

});

/**
 * 初始化订单列表
 * @returns
 */
// NameArray=[];
function initRoomTable(){
//	var $roomTableForm = $(".room-table-form")
	var settings = {
	        url: ctx + "diningroom/list",
	        pageSize: 10,
	        queryParams: function (params) {
	            return {
	                pageSize: params.limit,
	                pageNum: params.offset / params.limit + 1,
//	                resident:$roomTableForm.find("input[name='resident']").val().trim(),
//	                checkinTime:$roomTableForm.find("input[name='checkinTime']").val().trim(),
//	                orderStatus:$roomTableForm.find("select[name='orderStatus']").val(),
	            }
	        },
	        columns: [{
		            field: '12',
		            title: '序号',
	            	formatter: function (value, row, index) {
	            		return ++index;
	                }
		        }, {
		        	field: 'id',
		        	visible: false
		        },{
		            field: 'name',
		            title: '餐厅名称',
//		            formatter: function (value) {
//		            	NameArray.push({"name":value})
//		            	return value;
//	                }
		        }, {
		            field: 'place',
		            title: '用餐地点'
		        }, {
		            field: 'unitPrice',
		            title: '早餐单价'
		        }, {
		            field: 'openingTime',
		            title: '用餐时间'
		        }, {
		            field: 'phone',
		            title: '联系方式'
		        }, {
		            field: 'status',
		            title: '状态',
	            	formatter: function (value, row, index) {
	            		if (value === '0') return '关闭';
	            		if (value === '1') return '开启';
	                }
		        }, {
		            field: 'status',
		            title: '操作',
		            formatter : function(value, row, index){
		            	var diningroomId = row.id;
		            	if (value == '0')  return '<button type="button" class="btn btn-success" onclick="changeState('+diningroomId+',\'' + 1 + '\')" >开启</button>&nbsp<button type="button"  data-toggle="modal" data-target="#dining-add" class="btn btn-default" onclick="edit('+diningroomId+')">编辑</button>';
		            	if (value == '1')  return '<button type="button" class="btn btn-danger" onclick="changeState('+diningroomId+',\'' + 0 + '\')" >关闭</button>&nbsp<button type="button"  data-toggle="modal" data-target="#dining-add" class="btn btn-default" onclick="edit('+diningroomId+')">编辑</button>';
		           
		            }
		        }
	        ]
	    };
	$MB.initTable("orderTable", settings);
}


function search() {
    $MB.refreshTable('orderTable');
}

function refresh() {
    $(".room-table-form")[0].reset();
    $MB.refreshTable('orderTable');
}

//改变状态
function changeState(diningroomId,status) {
    $.post(ctx + "diningroom/changestate",{"id":diningroomId,"status":status}, function (r) {
        if (r.code === 0) {
        	$MB.n_success(r.msg);
        	$MB.refreshTable('orderTable');
        } else {
            $MB.n_warning(r.msg);
        }
    });
}
var nameR='';
//查询单个
function edit(diningroomId) {
	
/*	$("#member-add-modal-title").html("编辑餐厅")*/
	isEdit=true;
	
    $.post(ctx + "diningroom/single",{"id":diningroomId}, function (r) {
    	nameR=r.name;
    	console.log(nameR)
    	$("#name").val(r.name)
    	
    	$("#place").val(r.place)
    	var starTime=r.openingTime.slice(0,5)
    	var endTime=r.openingTime.slice(6)
    	$("#openingTime").val(starTime)
    	
    	$("#openingTimeE").val(endTime)
    	
    	$("#unitPrice").val(r.unitPrice)
    	$("#phone").val(r.phone)
    	$("#diningRoomid").val(r.id)
    	
    	console.log(r)
    	});
}

function closeModal() {
    $MB.closeAndRestModal("dining-add");
}

$(function () {
    $("#dining-add .btn-save").click(function () {
    	addmember();
    });
	$("#dining-add .btn-close").click(function () {
        closeModal();
    });
	
});

function add(){
	/*信息校验*/
	var name=$("#name").val();
    var place=$("#place").val();
	var openingTime=$("#openingTime").val();
	var endTime=$("#openingTimeE").val()
	var unitPrice=$("#unitPrice").val();
	var phone=$("#phone").val();
	var id=$("#diningRoomid").val()
	var errorArray=[];
	/*餐厅名称规则：汉字和字母*/
	if(name!=''){
		if(!(/^[a-zA-Z\u4e00-\u9fa5]+$/.test(name))){ 
			
			$MB.n_warning("餐厅名称不合法");
			errorArray.push(1) 
			
	    }else{
	    	console.log(nameR)
	    	console.log(name)
	    	console.log(nameR===name)
	    	if(nameR===name){
	    		
	    	}else{
	    		$.ajax({
					type : "post",
					url :  "diningroom/checkRepeat",
					dataType : "json",
					data : {
						"name":name,
					},
					async : false,
					success : function(r) {
						if(r.code==500){
			    			$MB.n_warning("餐厅名称已存在");
							errorArray.push(9) 
			    		}
					},
					error : function() {
						 $MB.n_warning("网络故障,请联系管理员");
					}
		         })
	    	
	    	}
	    	
	}
	}
//	if(name!=''){
//		for(var i=0;i<NameArray.length;i++){
//			if(NameArray[i].name==name){
//				$MB.n_warning("餐厅名称重复");
//				errorArray.push(0) 
//			}
//		}
//	} 
	/*地址*/
	if(place!=''){
//		if(!(/^[1-9][a-zA-Z\u4e00-\u9fa5][1-9]+$/.test(place))){ 
//			$MB.n_warning("餐厅地址不合法");
//			errorArray.push(2) 
//	    }
		var txt=new RegExp("[ ,\\`,\\~,\\!,\\@,\#,\\$,\\%,\\^,\\+,\\*,\\&,\\\\,\\/,\\?,\\|,\\:,\\.,\\<,\\>,\\{,\\},\\(,\\),\\'',\\;,\\=,\"]");
		if((txt.test(place))){ 
			$MB.n_warning("餐厅地址不合法");
			errorArray.push(2) 
	    }
	}
	
	if(openingTime!=''&&endTime!=''){
		if($("#openingTime").val()>$("#openingTimeE").val()){
				$MB.n_warning("时间范围不合法");
				errorArray.push(5) 
		   
		}
	 }
	
	
	/*金额*/
	if(unitPrice!=''){
//		if(!(/^([1-9]\d{0,2})|([1-4]\d{3})|(5[0-5]\d{2})|(56[0-6]\d)|(567[0-8]).$/.test(unitPrice))){ 
//			$MB.n_warning("单价不合法");
//			errorArray.push(3) 
//	    }
		  var r = /^\+?[1-9][0-9]*$/;//正整数
				if(!(r.test(unitPrice))){ 
					$MB.n_warning("单价不合法");
					errorArray.push(3) 
			    }
	}
	
	//电话号码
	if(phone!=''){
		var regx = /^[0-9\-*]+$/;
		if(!regx.test(phone)){ 
			$MB.n_warning("餐厅号码不合法");
			errorArray.push(4) 
	    }
	}
	
	console.log(errorArray)
	if(errorArray.length!=0){
		return
	}
	if(name==''||place==''||openingTime==''||unitPrice==''||phone==''||$("#openingTime").val()==''||$("#openingTimeE").val()==''){
		$MB.n_warning("餐厅信息不完整");
		return
	}
	
	
	if(isEdit==true){
		/*var name=$("#name").val();
		var place=$("#place").val();
		var openingTime=$("#openingTime").val();
		var unitPrice=$("#unitPrice").val();
		var phone=$("#phone").val();*/
		$.ajax({
			type : "post",
			url :  "diningroom/update",
			dataType : "json",
			data : {
				"name":name,
				"place":place,
				"openingTime":openingTime+"-"+endTime,
				"unitPrice":unitPrice,
				"phone":phone,
				"id":id
			},
			async : true,
			success : function(r) {
				if (r.code === 0) {
		        	$MB.n_success("保存成功");
		        	$MB.refreshTable('orderTable');
		        	closeModal();
		        } else {
		            $MB.n_warning(r.msg);
		        }
			},
			error : function() {
				 $MB.n_warning("网络故障,请联系管理员");
			}
		});
	}else{
		/*var name=$("#name").val();
		var place=$("#place").val();
		var openingTime=$("#openingTime").val();
		var unitPrice=$("#unitPrice").val();
		var phone=$("#phone").val();*/
		$.ajax({
			type : "post",
			url :  "diningroom/add",
			dataType : "json",
			data : {
				"name":name,
				"place":place,
				"openingTime":openingTime+"-"+endTime,
				"unitPrice":unitPrice,
				"phone":phone
			},
			async : true,
			success : function(r) {
				if (r.code === 0) {
		        	$MB.n_success(r.msg);
		        	$MB.refreshTable('orderTable');
		        	closeModal();
		        } else {
		            $MB.n_warning(r.msg);
		        }
			},
			error : function() {
				 $MB.n_warning("网络故障,请联系管理员");
			}
		});
	}
	
}
